package controller

import (
	"blogger/dao"
	"blogger/global"
	"blogger/model"
	"blogger/util"
	"blogger_protoes/protoes"
	"context"
	"fmt"
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

// 注册用户
func RegisterUser(c *gin.Context) {
	nowTime := time.Now().Local()
	userInfo := &model.UserInfo{}
	userInfo.CreateTime = nowTime
	userInfo.LoginTime = nowTime
	userInfo.Status = "0" // 默认值0，用户正常
	if err := c.ShouldBindJSON(userInfo); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error":   err.Error(),
			"message": "参数错误",
		})
		return
	}
	userInfo.Password = util.MD5(userInfo.Password)

	client := protoes.NewBlogDataClient(global.RPCConn)
	u, err := client.UserQueryWithUsername(context.Background(), &protoes.UserQueryWithUsernameRequest{Username: userInfo.Username})
	if err != nil {
		fmt.Println("调用grpc UserQueryWithUsername 失败：", err)
		return
	}
	if u.Id != 0 {
		c.JSON(http.StatusOK, gin.H{
			"isSuccess": false,
			"message":   "用户已存在",
		})
		return
	}
	fmt.Println(u)
	// 注册用户
	userId, err := client.UserInsert(context.Background(), &protoes.User{
		Username:   userInfo.Username,
		Password:   userInfo.Password,
		CreateTime: util.TimeToSeconds(userInfo.CreateTime),
		LoginTime:  util.TimeToSeconds(userInfo.LoginTime),
		Status:     userInfo.Status,
	})
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"isSuccess": false,
			"message":   "添加用户失败",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"isSuccess": true,
		"message":   "添加用户成功",
		"userId":    userId,
	})
	return
	//// 查询用户是否存在
	//u, err := dao.GetUserByUsername(userInfo.Username)
	//if err == nil {
	//	c.JSON(http.StatusOK, gin.H{
	//		"isSuccess": false,
	//		"message":   "用户已存在",
	//	})
	//	return
	//}
	//fmt.Println(u)
	//
	//userId, err := dao.RegisterUser(*userInfo)
	//if err != nil {
	//	c.JSON(http.StatusOK, gin.H{
	//		"isSuccess": false,
	//		"message":   "添加用户失败",
	//	})
	//	return
	//}
	//c.JSON(http.StatusOK, gin.H{
	//	"isSuccess": true,
	//	"message":   "添加用户成功",
	//	"userId":    userId,
	//})
}

// 跳转登录页
func LoginHtml(c *gin.Context) {
	c.HTML(http.StatusOK, "login.html", gin.H{})
}

// 登录
func Login(c *gin.Context) {
	//GlobalSessions.SessionStart(c)
	// 获取用户名
	userInfo := &model.UserInfo{}
	if err := c.ShouldBindJSON(userInfo); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error":   err.Error(),
			"message": "参数转换错误",
		})
		return
	}
	user, err := dao.GetUserByUsername(userInfo.Username)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"isSuccess": false,
			"message":   "用户名或密码错误",
		})
		return
	}
	// 登录成功
	if user.Password == util.MD5(userInfo.Password) {
		// 设置session
		session := sessions.Default(c)
		session.Set("username", userInfo.Username)
		session.Set("userId", userInfo.Id)
		session.Save()
		// 更新用户表的登录时间
		dao.UpdateUserInfoLoginTimeByUserId(userInfo.Id)
		// 重定向到首页
		c.JSON(http.StatusOK, gin.H{
			"isSuccess": true,
			"message":   "登录成功",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"isSuccess": false,
		"message":   "登录失败",
	})
}

// 判断是否登录
func IsLogin(c *gin.Context) bool {
	session := sessions.Default(c)
	username := session.Get("username")
	if username != nil {
		return true
	}
	return false
}

// 退出登录
func Exit(c *gin.Context) {
	session := sessions.Default(c)
	session.Clear()
	session.Save()
	c.Redirect(http.StatusMovedPermanently, "/")
}
